package com.qf.zyh.web;

import com.qf.zyh.util.FileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/file")
@MultipartConfig(maxFileSize = 1024*1024*10,maxRequestSize = 1024*1024*100)
public class FileCont extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method){
            case "upload":
                this.upload(req,resp);
                break;
        }
    }

    private void upload(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Part userfile = req.getPart("userfile");
            //InputStream inputStream = userfile.getInputStream();
            //获取out内的xx路径
            String realPath = req.getServletContext().getRealPath("/WEB-INF/upload");
            //通过散列存储，来给文件不同路径。
            //userfile.write(realPath+"/"+userfile.getSubmittedFileName());
            //通过工具类的uuid获取不重复的文件名
            String newFile = FileUtil.getNewFile(userfile.getSubmittedFileName());
            //String s = realPath + "/" + newFile;
            //通过工具类的与运算获得二级三级路径，进行拼接
            realPath = FileUtil.getNewFilePath(realPath,newFile);
            //file对象
            File f = new File(realPath);
            System.out.println(f);
            System.out.println(f.exists());
            if (!f.exists()) {
                //不存在就创建
                boolean mkdir = f.mkdirs();
                System.out.println(mkdir);
            }
            System.out.println(realPath);
            userfile.write(realPath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }
}
